namespace Vanilla.UI

// MENU ITEM
class MenuItem (Button):
	def constructor (p as Box, t as string, c as callable):
		super(p, t, c)
		Rounding = 2
	
	def constructor (p as Box, t as string, m as Menu):
		self(p, t, {PopUp(m)})
	
	// A menu item treats mouse-ups as clicks even if the mouse was first pressed in another widget
	override def MouseUp (b as MouseButton, x as double, y as double):
		Click(b,x,y)

// MENU SECTION
class MenuSection (Column):
	class Label (Vanilla.UI.Label):
		def constructor (p as Box, t as string):
			super(p, t)
			Colour = Colour.Grey
		
		override MinSize as Size:
			get:
				return Size(super().Width, System.Math.Max(super().Height, 25.0))

	Name as string:
		get:
			return TitleBar.Text
		set:
			TitleBar.Text = value
	
	TitleBar as Label
	
	def constructor (p as Box, n as string):
		super(p)
		TitleBar = Label(self, n)
		DrawFrame = false
		Spacing = 0
	

// MENU
class Menu (TopLevel):
	// Keeps the menu within the bounds of the screen
	override Rect as Rect:
		set:
			unless Parent == null:
				if value.X2 > Parent.Size.Width:
					//print "sooooop ${value.X} ${Parent.Size.Width} ${value.Width} ${MinSize.Width}"
					value.X = Parent.Size.Width - value.Width
					value.X2 = Parent.Size.Width
					//print "${value.X}"
			super(value)

	public Contents as Column
	
	def constructor (p as Desktop):
		super(p)
		Contents = Column(self)
		Contents.DrawFrame = false
		Size = MinSize
	
	def constructor ():
		self(null)
	
	def AddItem (g as Gadget):
		Contents.Add(g)
	
	def AddItem (t as string, c as callable):
		MenuItem(Contents, t, c)
		Pack()
	
	def AddItem (t as string, m as Menu):
		MenuItem(Contents, t, m)
		Pack()
	
	def AddItem (s as string, t as string, c as callable):
		section as MenuSection
		unless Contents is null or Contents.Children is null:
			for i in Contents.Children:
				if i isa MenuSection:
					_s = i as MenuSection
					section = _s if _s.Name == s
		section = MenuSection(Contents, s) if section is null
		
		MenuItem(section, t, c)
	
	def RemoveItem (g as Gadget):
		Contents.Remove(g)
		Pack()
	
	//override MinSize as Size:
	//	get:
	//		return Size(100,100)
	
	override def BringToFront ():
		Order = Parent.Children.Length-1
		Redraw()
	
	override def MouseDown (b as MouseButton, x as double, y as double):
		if Size.Contains(x,y):
			super(b,x,y)
		else:
			Close()
	
	override def MouseUp (b as MouseButton, x as double, y as double):
		super(b,x,y)
		Close()
	
	override def Reparented (o as Box, n as Box):
		GrabMouse()
	
	def Close ():
		ReleaseMouse()
		Parent.Remove(self) unless Parent == null
